/*

* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Smart-Shop开源商城系统/ Java商城-首选电商平台系统 请务必保留此注释头信息
* |     开源地址: https://gitee.com/ningbo-qishan/gruul-mall
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     可正常分享和学习源码,未经授权 不可商用！
* |     商业版中台购买/开源版商业授权 联系技术客服
* |     官网:  https://www.73app.cn/
* ------------------------------------------------------------------------
* ------------------------------------------------------------------------
* |     Copyright (c) 2016-2999 宁波启山智软科技有限公司
* |     版权所有 ,侵权必究！
* ------------------------------------------------------------------------

*/
package com.medusa.gruul.integral.web.remote;

import com.alibaba.fastjson.JSON;
import com.medusa.gruul.account.api.model.IntegraChangelDto;
import com.medusa.gruul.common.core.annotation.EscapeLogin;
import com.medusa.gruul.common.core.exception.ServiceException;
import com.medusa.gruul.common.core.util.Result;
import com.medusa.gruul.common.data.tenant.ShopContextHolder;
import com.medusa.gruul.common.data.tenant.TenantContextHolder;
import com.medusa.gruul.integral.api.entity.IntegralShop;
import com.medusa.gruul.integral.api.model.*;
import com.medusa.gruul.integral.mq.Sender;
import com.medusa.gruul.integral.service.*;
import com.medusa.gruul.integral.web.enums.IntegralOperationTypeEnum;
import com.medusa.gruul.integral.web.model.dto.manager.IntegralShopDto;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description: 提供积分商家设置的积分折扣规则
 * @Author: xiaoq
 * @Date : 2019/12/7 16:11
 */
@RestController(value = "remoteIntegralService")
@RequestMapping("/")
@Slf4j
public class RemoteIntegralService {
	@Autowired
	private IIntegralShopService integralShopService;

	@Autowired
	private IIntegralDetailService integralDetailService;

	@Autowired
	private IIntegralCouponOrderService integralCouponOrderService;

	@Autowired
	private IIntegralRuleService integralRuleService;

	@Autowired
	private IIntegralOrderService integralOrderService;

	@Autowired
	private Sender sender;

	/**
	 *
	 * 获取商家设置的抵扣规则
	 *
	 * @param shopId 商家租户id
	 * @return com.medusa.gruul.integral.api.model.DiscountInfoDto
	 */
	@GetMapping(value = "discountInfo")
	@ApiOperation(value = "获取商家积分抵扣规则,已交由finance模块维护")
	@EscapeLogin
	public DiscountInfoDto discountInfo(
			@RequestParam(value = "shopId", required = true) @NotNull(message = "shopId不能为空") String shopId) {
		return integralShopService.getDiscountInfo(shopId);
		//该数据已交由财务模块通用设置维护
	}


	/**
	 * 积分归还 部分订单取消可进行积分归还 如:超时未支付
	 *
	 * @param userId  用户Id
	 * @param integralValue 归还的积分值
	 * @return
	 */
    @GetMapping(value = "giveBack")
    @ApiOperation(value = "归还")
	@EscapeLogin
	public Boolean integralReturn(
			@RequestParam(value = "userId", required = true) @NotNull(message = "用户id不能为null") String userId,
			@RequestParam(value = "integralValue", required = true) @NotNull(message = "积分值不能为空") BigDecimal integralValue) {
		String tenantId = TenantContextHolder.getTenantId();
        String shopId = ShopContextHolder.getShopId();
        log.info("input {}用户id: +"+userId+" {}积分值: "+integralValue);
		//jdk 1.8以后 该方法过时
		integralValue = integralValue.setScale(2, BigDecimal.ROUND_HALF_UP);

		//生成积分明细记录
		if ((integralValue.compareTo(BigDecimal.ZERO) == 1) || (integralValue.compareTo(BigDecimal.ZERO) == -1)) {
			Boolean flag = integralDetailService.addIntegralDetailRecord(userId, tenantId, integralValue);
			if (!flag) {
				return Boolean.FALSE;
			}
			//用户扣除积分dto 封装
			IntegraChangelDto integraChangelDto = new IntegraChangelDto();
			integraChangelDto.setOption(IntegralOperationTypeEnum.INCREASE.getStatus());
			integraChangelDto.setUserId(userId);
			integraChangelDto.setValue(integralValue);
			integraChangelDto.setTenantId(tenantId);
			sender.sendIntegralDeductionMessage(integraChangelDto);
			return Boolean.TRUE;
		}
		return Boolean.TRUE;
	}


	/**
	 * 积分扣减 使用积分 进行扣减
	 * @param userId
	 * @param integralValue
	 */
	@GetMapping(value = "deduction")
	@ApiOperation(value = "积分扣减 -- 扣除积分是强事物性的 交由用户模块进行操作(扣除积分为用户模块,该处只生成扣减积分明细)")
	@EscapeLogin
	public Boolean integralDeduction(
			@RequestParam(value = "userId", required = true) @NotNull(message = "用户id不能为null") String userId,
			@RequestParam(value = "integralValue", required = true) @NotNull(message = "积分值不能为空") BigDecimal integralValue) {
		String tenantId = TenantContextHolder.getTenantId();
		if (integralValue.compareTo(BigDecimal.ZERO) == 1) {
			//生成积分明细记录
			Boolean flag = integralDetailService.subtractIntegralDetailRecord(userId, tenantId, integralValue);
			if (!flag) {
				return flag;
			}
			//扣除积分是强事物性的 交由用户模块进行操作
		}
		return Boolean.TRUE;
	}


	/**
	 * 兑换积分优惠券
	 *
	 * @param integralCouponDto 生成订单所需值
	 * @return 是否成功
	 */
	@PutMapping(value = "conversion")
	@ApiOperation(value = "兑换积分优惠劵,数值由discount 模块提供")
	@EscapeLogin
	public Result conversionIntegralCoupon(@RequestBody IntegralCouponDto integralCouponDto) {
		//.生成优惠券订单 并通知用户扣积分
		Result result = integralCouponOrderService.addIntegralCouponOrder(integralCouponDto);
		System.out.println(result);
		return result;
	}


	/**
	 *  生成积分商城所需 默认值
	 * @param shopId  商铺id
	 * @param tenantId 租户id
	 * @return 是否成功
	 */
	@PostMapping(value = "generate/default/values")
	@ApiOperation(value = "生成积分默认值,创建店铺时使用")
	@EscapeLogin
	Boolean integralDefault(
			@RequestParam(value = "shopId", required = true) @NotNull(message = "shopId不能为空") String shopId,
			@RequestParam(value = "tenantId", required = true) @NotNull(message = "tenantId不能为空") String tenantId) {
		BigDecimal ceiling = new BigDecimal(3);
		BigDecimal ratio = new BigDecimal(2);
		IntegralShopDto integralShopDto = new IntegralShopDto();
		integralShopDto.setCeiling(ceiling);
		integralShopDto.setRatio(ratio);
		integralShopDto.setTenantId(tenantId);
		integralShopDto.setShopId(shopId);
		integralShopDto.setType(false);
		IntegralShop integralShop = integralShopDto.coverIntegralShop();
		integralShop.setCreateTime(LocalDateTime.now());
		integralShop.setUpdateTime(LocalDateTime.now());
		integralShop.setDeleted(false);
		boolean save = integralShopService.saveIntegralShopDefault(integralShop);
		if (!save) {
			throw new ServiceException("积分商城默认值生成失败");
		}

		Boolean flag = integralRuleService.saveIntegralDefaultRule(integralShop.getId(), shopId, tenantId);
		return flag;
	}

	/**
	 获取商城信息 积分商城状态 签到状态 步数状态
	 *
	 * @param
	 * @return map<"  名称   "      ,      "   开启状态    ">
	 */
	@GetMapping("functionInfo")
	@ApiOperation(value = "生成积分默认值,创建店铺是使用")
	@EscapeLogin
	public ShopFunctionInfoVo getShoppingFunctionInfo(String shopId) {
		return integralShopService.getShopFunctionInfo(shopId);
	}


	/**
	 * 获取用户信息
	 * @return
	 */
	@PostMapping("get/userInfo/{shopUserId}")
	@ApiOperation(value = "用户信息 ,提供数据供聚合接口使用")
	@EscapeLogin
	public UserInfoVo getUserInfo(@PathVariable(value = "shopUserId") String shopUserId) {
		return integralDetailService.getUserInfo(shopUserId);
	}

	/**
	 * 积分订单打印并发货
	 *
	 * @param integralOrderDelivery
	 * @return
	 */
	@ApiOperation("积分订单打印并发货")
	@GetMapping("print/delivery")
	@EscapeLogin
	public int doLogisticsIntegralOrderDelivery(
			@RequestParam(value = "integralOrderDelivery") String integralOrderDelivery) {
		List<IntegralOrderDeliveryDto> integralOrderDeliveryDtos = JSON
				.parseArray(integralOrderDelivery, IntegralOrderDeliveryDto.class);
		if (null == integralOrderDeliveryDtos || 0 == integralOrderDeliveryDtos.size()) {
			return 0;
		}
		int i = integralOrderService.doLogisticsIntegralOrderDelivery(integralOrderDeliveryDtos);
		System.out.println(i);
		return i;
	}

	/**
	 *  根据积分订单id获取订单信息 vo
	 *
	 * @param integralOrderId
	 * @return
	 */
	@GetMapping("get/integralOrderInfo")
	@ApiOperation("根据积分订单id获取订单信息")
	@EscapeLogin
	public IntegralOrderVo integralOrderInfo(
			@RequestParam(value = "integralOrderId", required = true) @NotNull Long integralOrderId) {
		IntegralOrderVo integralOrderVo = integralOrderService.integralOrderInfo(integralOrderId);
		System.out.println(integralOrderVo.toString());
		return integralOrderVo;
	}


	/**
	 * 使用积分 兑换会员卡
	 *
	 * @param shopUserId  用户id
	 * @param integralValue 积分值
	 * @return
	 */
	@EscapeLogin
	@ApiOperation("使用积分,兑换会员卡")
	@PostMapping("conversion/clubCard")
	public Result conversionClubCard(
			@RequestParam(value = "shopUserId", required = true) @NotNull(message = "用户id不能为null") String shopUserId,
			@RequestParam(value = "integralValue", required = true) @NotNull(message = "积分值不能为空") BigDecimal integralValue) {
		Result result = integralDetailService.useIntegralConversionClubCard(shopUserId, integralValue);
		return result;
	}
}


